﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace Base.Common.Converters
{
    [ValueConversion(typeof(bool), typeof(Visibility))]
    public class BoolToVisibilityConverter : ConverterBase
    {
        /// <summary>
        /// 是否反转转换结果
        /// </summary>
        public bool Invert { get; set; } = false;

        /// <summary>
        /// False值对应的Visibility枚举
        /// </summary>
        public Visibility FalseValue { get; set; } = Visibility.Collapsed;

        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool tempBool = value?.ToString()?.ToBool() ?? false;
            if (tempBool)
            {
                return tempBool == Invert ? FalseValue : Visibility.Visible;
            }
            return FalseValue;
        }

        public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                Visibility v = (Visibility)value;
                if (v == Visibility.Visible)
                    return !Invert;
                return Invert;
            }
            catch
            {
                return false;
            }
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }
    }
}
